/**
 * Copyright (C), 2015-2019, XXX有限公司
 * FileName: CustFilingController
 * Author:   Administrator
 * Date:     2019/6/10 11:47
 * Description: 客户建档controller
 * History:
 * <author>          <time>          <version>          <desc>
 * 作者姓名           修改时间           版本号              描述
 */
package com.sunlord.controller;

import OThinker.Common.DateTimeUtil;
import OThinker.Common.Organization.Models.User;
import OThinker.H3.Controller.ControllerBase;
import OThinker.H3.Controller.RestfulApi.Entity.RestfulApiResult;
import OThinker.H3.Entity.Instance.Data.InstanceData;
import OThinker.H3.Entity.Instance.InstanceContext;
import OThinker.H3.Entity.Query;
import OThinker.H3.Portal.webservices.Entity.BPMServiceResult;
import OThinker.H3.Portal.webservices.impl.BPMServiceImpl;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.h3bpm.base.user.UserValidator;
import com.h3bpm.base.util.AppUtility;
import com.sunlord.dto.BpcMaster;
import com.sunlord.dto.CustFilingX3Data;
import com.sunlord.dto.SunlordResult;
import com.sunlord.fianl.SunlordTrueFalse;
import com.sunlord.service.SunlordService;
import com.sunlord.workflow.WorkflowNewParam;
import com.sunlord.workflow.WorkflowNewRet;
import data.DataColumnCollection;
import data.DataException;
import data.DataRowCollection;
import data.DataTable;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import java.util.*;

/**
 * 〈一句话功能简述〉<br>
 * 〈客户建档controller〉
 *
 * @author Administrator
 * @create 2019/6/10
 * @since 1.0.0custFilingWriteBack
 */
@RestController()
@RequestMapping("/sunlord")
public class SunlordController extends  ControllerBase {
    private static final Logger LOGGER = LoggerFactory.getLogger(SunlordController.class);

    private static final BPMServiceImpl bpmService = new BPMServiceImpl();
    @Autowired
    private SunlordService sunlordService;





    /**
     *  新建档案 写到主数据   7.3
     *
     * @param instanceId
     * @return
     */
    @RequestMapping(value = "custFilingWriteBack")
    public RestfulApiResult custFilingWriteBack(String instanceId) {
        RestfulApiResult result = null;
        try {
            InstanceData sourceData = new InstanceData(AppUtility.getEngine(), instanceId, User.AdministratorID);
            if (sourceData != null ){
                SunlordResult rst =  custFlingDataToMastData(sourceData);
                if (rst.isSuccess()){
                    result = custMasterDataToX3(rst.getMsg(), null);
                    result.setMsg((String) sourceData.getBizObject().GetValue("DATAMASTINSTID"));
                }else{
                    result = RestfulApiResult.fail("流程写入主数据失败");
                }
            }else {
                result = RestfulApiResult.fail("流程实例不存在");
            }
        } catch (Exception e) {
            e.printStackTrace();
            LOGGER.error(e.getMessage());
            result = RestfulApiResult.fail("系统异常");
        }
        return result;
    }


    /**
     *  流程数据 到 主数据 7.3
     * @return
     */
    public SunlordResult custFlingDataToMastData(InstanceData sourceData) throws Exception {
        SunlordResult result = SunlordResult.fail("");
        //判断主数据里是否存在
        String datamastinstid = (String) sourceData.getBizObject().GetValue("DATAMASTINSTID");
        String mastObjectid = null;
        if (datamastinstid != null ){

            if(!datamastinstid.equals("系统异常")){
                InstanceData instanceDataMaster = new InstanceData(AppUtility.getEngine(), datamastinstid, User.AdministratorID);
                if (instanceDataMaster == null){
                    datamastinstid = null;
                }else{
                    mastObjectid = instanceDataMaster.getInstanceContext().getBizObjectId();
                }
            }else{
                datamastinstid = null;
            }

        }

        if (datamastinstid == null){
            JSONObject jsonObject = new JSONObject();

            jsonObject.put("BPRNAM",sourceData.getBizObject().GetValue("BPRNAM"));
            jsonObject.put("BPCSNCDAT",DateTimeUtil.format(new Date() ));

            WorkflowNewParam workflowParam =  new WorkflowNewParam("BPCMASTER",User.AdministratorAlias, "true", jsonObject.toString());

            WorkflowNewRet ret = this.exworkflow(workflowParam);

            if (ret.isSuccess()){

                HashMap<String, String> schemaNameValue = new HashMap<>(16);

                schemaNameValue.put("BUSSTAMASTER","BUSSTA");
                schemaNameValue.put("BPADDRESSMASTER","BPADDRESS");
                schemaNameValue.put("CONTACTMASTER","CONTACT");
                schemaNameValue.put("CRMBPCMASTER","CRMBPC");
                schemaNameValue.put("CRMBPCITMMASTER","CRMBPCITM");


                InstanceData destData = new InstanceData(AppUtility.getEngine(), ret.getInstanceID(), User.AdministratorID);

                boolean b = sunlordService.custModify(sourceData, destData, schemaNameValue);
                if (b){
                    sourceData.getBizObject().SetValue("DATAMASTINSTID",destData.getInstanceId());
                    sourceData.Submit();
                    result = SunlordResult.success(destData.getInstanceContext().getBizObjectId());
                }else{
                    result = SunlordResult.fail("流程数据copy 到主数据失败...");
                }
            }
        }else{
            LOGGER.info("已存在主数据流程instanceid:"+datamastinstid);
            result = SunlordResult.success(mastObjectid);
        }

        return  result;
    }


    @RequestMapping("copytoMaster")
    public String copytoMaster(String instId,String MastInstId) throws Exception {
        InstanceData sourceData = new InstanceData(AppUtility.getEngine(), instId, User.AdministratorID);

        String datamastinstid = (String) sourceData.getBizObject().GetValue("DATAMASTINSTID");

        if (MastInstId != null && MastInstId.equals(datamastinstid)){

            HashMap<String, String> schemaNameValue = new HashMap<>(16);

            schemaNameValue.put("BUSSTAMASTER","BUSSTA");
            schemaNameValue.put("BPADDRESSMASTER","BPADDRESS");
            schemaNameValue.put("CONTACTMASTER","CONTACT");
            schemaNameValue.put("CRMBPCMASTER","CRMBPC");
            schemaNameValue.put("CRMBPCITMMASTER","CRMBPCITM");


            InstanceData destData = new InstanceData(AppUtility.getEngine(), datamastinstid, User.AdministratorID);

            boolean b = sunlordService.custModify(sourceData, destData, schemaNameValue);

            return String.valueOf(b);
        }

        return String.valueOf(false);
    }


    private void setMastId(String dataMastInstId, String xs006Id) throws Exception {
        String soursql  = String.format("UPDATE I_XS006 SET DATAMASTINSTID = '%s'  WHERE OBJECTID = '%s'",dataMastInstId,xs006Id);

        sunlordService.ExecuteEngineSql(Arrays.asList(soursql));
    }

    public WorkflowNewRet exworkflow( WorkflowNewParam param){
        try {

            BPMServiceResult result = bpmService.StartWorkflowNew("H3", "Authine", param.getWorkflowCode(), param.getUserCode(), param.getFinishStart(), param.getParamValues());
            return setRet(result);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 设置返回值
     * @param result BPMServiceResult
     * @return WorkflowNewRet
     */
    private WorkflowNewRet setRet(BPMServiceResult result) {
        WorkflowNewRet ret = new WorkflowNewRet();
        ret.setSuccess(result.isSuccess());
        ret.setMessage(result.getMessage());
        ret.setInstanceID(result.getInstanceId());
        ret.setWorkItemID(result.getWorkItemId());
        ret.setWorkItemUrl(result.getWorkItemUrl());
        return ret;
    }

    /**
     *  建档数据到x3  7.3
     * @param instanceBizObjectId
     * @param instanceEditBizObjectId
     * @return
     */
    @RequestMapping("custMasterDataToX3")
    public RestfulApiResult custMasterDataToX3(String instanceBizObjectId,String instanceEditBizObjectId) {
         RestfulApiResult result = null;
        try {

            String  masterCols = "*";
            String  bpAddressCols = "*";
            String  contactCols = "*";

            //实例数据sql
            String sqlMaster = "SELECT "+masterCols+" FROM " + BpcMaster.I_BPC_MASTER +" WHERE OBJECTID = '" + instanceBizObjectId+"'";
            //收获地址
            String sqlBpAddress = "SELECT "+bpAddressCols+" FROM "+BpcMaster.I_BPADDRESS_MASTER +" WHERE PARENTOBJECTID =  '" + instanceBizObjectId +"'";
            //联系人sql
            String sqlContact = "SELECT "+contactCols+" FROM "+ BpcMaster.I_CONTACT_MASTER +" WHERE PARENTOBJECTID =  '" + instanceBizObjectId +"'";

            Query query = ControllerBase.getEngine().getQuery();

            DataTable dataMaster = query.QueryTable(sqlMaster);
            if (dataMaster.getRows().size() == 0) {
                return  RestfulApiResult.fail("未查到实例数据");
            }
            if(dataMaster.getRows().size()>1){
                return RestfulApiResult.fail("实例数据数据查询出多条");
            }
            List<Map<String, Object>> masterParam = analysisBizObjectToListMap(dataMaster);
            if(masterParam.isEmpty()){
                return RestfulApiResult.fail("转换实例数据为空");
            }

            DataTable dataBpAddress = query.QueryTable(sqlBpAddress);
            DataTable dataContact = query.QueryTable(sqlContact);

            List<Map<String, Object>> bpAddressParam = analysisBizObjectToListMap(dataBpAddress);
            List<Map<String, Object>> contactParam = analysisBizObjectToListMap(dataContact);


            if (instanceEditBizObjectId != null && instanceEditBizObjectId.length()>0){

                masterParam.get(0).put("OBJECTID",instanceEditBizObjectId);
                for (int i = 0; i < bpAddressParam.size(); i++) {
                    bpAddressParam.get(i).put("PARENTOBJECTID",instanceEditBizObjectId);
                }

                for (int i = 0; i < contactParam.size(); i++) {
                    contactParam.get(i).put("PARENTOBJECTID",instanceEditBizObjectId);
                }

            }

            boolean success = sunlordService.custFilingSaveToX3(new CustFilingX3Data(masterParam.get(0), bpAddressParam, contactParam));

            if (success){
                result = RestfulApiResult.success("建档数据回写中间表成功");
            }else{
                result = RestfulApiResult.fail("系统异常");
            }
        } catch (Exception e) {
            e.printStackTrace();
            LOGGER.error(e.getMessage());
            result = RestfulApiResult.fail("系统异常");
        }
        return result;
    }




    /**
     *  变更回写到主数据  -- 7.3
     * @param sInstanceId
     * @param destInstanceId
     * @return
     */
    @RequestMapping(value = "custFilingDataChangeWriteBack")
    public RestfulApiResult custFilingDataChangeWriteBack(String sInstanceId,String destInstanceId){
        HashMap<String, String> schemaNameValue = new HashMap<>(16);

        schemaNameValue.put("BUSSTAMASTER","BUSSTACHG");
        schemaNameValue.put("BPADDRESSMASTER","BPADDRESSCHG");
        schemaNameValue.put("CONTACTMASTER","CONTACTCHG");
        schemaNameValue.put("CRMBPCMASTER","CRMBPCCHG");
        schemaNameValue.put("CRMBPCITMMASTER","CRMBPCITMCHG");
        RestfulApiResult result = custChangeToMasterAndX3(sInstanceId, destInstanceId,schemaNameValue,true);
        return  result;
    }

    /**
     *  FieldInfoChg 行业信息变更  回写 数据
     * @param sInstanceId
     * @param destInstanceId
     * @return
     */
    @RequestMapping(value = "fieldInfoChgWriteBack")
    public RestfulApiResult fieldInfoChgWriteBack(String sInstanceId,String destInstanceId){
        HashMap<String, String> schemaNameValue = new HashMap<>(16);

        RestfulApiResult result = custChangeToMasterAndX3(sInstanceId, destInstanceId,schemaNameValue,false);
        return  result;
    }


    /**
     *  BPCAddInfoCHG  客户地址联系人变更  回写 数据
     * @param sInstanceId
     * @param destInstanceId
     * @return
     */
    @RequestMapping(value = "bpcAddInfoChgWriteBack")
    public RestfulApiResult bpcAddInfoChgWriteBack(String sInstanceId,String destInstanceId){
        HashMap<String, String> schemaNameValue = new HashMap<>(16);
//            地址联系人
        schemaNameValue.put( "BPADDRESSMASTER","BPADDRESSYW");
//            客户地址
        schemaNameValue.put( "CONTACTMASTER","CONTACTYW");
        RestfulApiResult result = custChangeToMasterAndX3(sInstanceId, destInstanceId,schemaNameValue,true);
        return  result;
    }




    /**
     *  变更数据到 主数 并 回写至X3
     * @param sInstanceId
     * @param destInstanceId
     * @param schemaNameValue  子表编码映射
     * @return
     */
    private RestfulApiResult custChangeToMasterAndX3(String sInstanceId, String destInstanceId,HashMap<String, String> schemaNameValue,boolean flag) {
        RestfulApiResult result = RestfulApiResult.fail("");
        try {

            InstanceData sourceData = new InstanceData(AppUtility.getEngine(), sInstanceId, User.AdministratorID);
            InstanceData destData = new InstanceData(AppUtility.getEngine(), destInstanceId, User.AdministratorID);

            //变更流程数据覆盖 建档流程数据
            if(!sunlordService.custModify(sourceData, destData, schemaNameValue)){
                result = RestfulApiResult.fail(String.format("建档变更数据覆盖建档数据失败,变更实例id:%s,建档实例id:%s",sInstanceId,destInstanceId ));
            }

            result.setMsg(destInstanceId);
            if (flag){
                if (result.getCode() == 0){
                    result = custMasterDataToX3(destInstanceId, null);
                }else{
                    result = RestfulApiResult.fail("流程写入主数据失败");
                }
            }


        } catch (Exception e) {
            e.printStackTrace();
            LOGGER.error(e.getMessage());
            result = RestfulApiResult.fail("系统异常");
        }
        return result;
    }

    /**
     * 发起变更流程
     * @param instanceId
     * @return
     */
    @RequestMapping("/startChangeCustDataMaster")
    public RestfulApiResult startChangeCustDataMaster(String instanceId,String loginCode){
        RestfulApiResult  result = RestfulApiResult.fail("");
        HashMap<String, String> schemaNameValue = new HashMap<>(16);

        schemaNameValue.put("BUSSTACHG"   ,    "BUSSTAMASTER");
        schemaNameValue.put("BPADDRESSCHG", "BPADDRESSMASTER");
        schemaNameValue.put("CONTACTCHG"  ,   "CONTACTMASTER");
        schemaNameValue.put("CRMBPCCHG"   ,    "CRMBPCMASTER");
        schemaNameValue.put("CRMBPCITMCHG", "CRMBPCITMMASTER");
        result = startFlowWorkAndCopyData(instanceId, loginCode,"BPCCHG",schemaNameValue);
        return  result;
    }

    /**
     * 客户地址联系人变更
     * @param instanceId
     * @return
     */
    @RequestMapping("/bpcAddInfoChg")
    public RestfulApiResult bpcAddInfoChg(String instanceId) {
        RestfulApiResult  result = RestfulApiResult.fail("");

        UserValidator userValidator = getUserValidator();
        if (userValidator != null && userValidator.getUserCode() != null ){

            HashMap<String, String> schemaNameValue = new HashMap<>(16);


//            地址联系人
            schemaNameValue.put("BPADDRESSYW", "BPADDRESSMASTER");
//            客户地址
            schemaNameValue.put("CONTACTYW"  ,   "CONTACTMASTER");


//            schemaNameValue.put("BUSSTACHG"   ,    "BUSSTAMASTER");
//            schemaNameValue.put("CRMBPCCHG"   ,    "CRMBPCMASTER");
//            schemaNameValue.put("CRMBPCITMCHG", "CRMBPCITMMASTER");
            result = startFlowWorkAndCopyData(instanceId, userValidator.getUserCode(),"BPCAddInfoCHG",schemaNameValue);
        }else{
            result.setMsg("用户未登陆");
        }
        return result;
    }
    /**
     * 行业信息变更
     * @param instanceId
     * @return
     */
    @RequestMapping("/fieldInfoChg")
    public RestfulApiResult fieldInfoChg(String instanceId){

        RestfulApiResult  result = RestfulApiResult.fail("");

        UserValidator userValidator = getUserValidator();
        if (userValidator != null && userValidator.getUserCode() != null ){

            HashMap<String, String> schemaNameValue = new HashMap<>(16);


//            schemaNameValue.put("BUSSTACHG"   ,    "BUSSTAMASTER");
//            schemaNameValue.put("BPADDRESSCHG", "BPADDRESSMASTER");
//            schemaNameValue.put("CONTACTCHG"  ,   "CONTACTMASTER");
//            schemaNameValue.put("CRMBPCCHG"   ,    "CRMBPCMASTER");
//            schemaNameValue.put("CRMBPCITMCHG", "CRMBPCITMMASTER");
            result = startFlowWorkAndCopyData(instanceId, userValidator.getUserCode(),"FieldInfoChg",schemaNameValue);
        }else{
            result.setMsg("用户未登陆");
        }
        return  result;
    }




    private RestfulApiResult startFlowWorkAndCopyData(String instanceId, String loginCode,String workflowCode, HashMap<String, String> subTabeCode) {
        RestfulApiResult result;
        try {
            if (instanceId != null){
                InstanceData sourceData = new InstanceData(AppUtility.getEngine(), instanceId, User.AdministratorID);
                if (sourceData != null){


                    Object bpcnum = sourceData.getBizObject().GetValue("BPCNUM");

                    if (bpcnum != null && !"".equals(bpcnum.toString().trim())){

                        JSONObject jsonObject = new JSONObject();

                        jsonObject.put("BPRNAM",sourceData.getBizObject().GetValue("BPRNAM"));
                        jsonObject.put("INSTID",instanceId);

                        WorkflowNewParam workflowParam =  new WorkflowNewParam(workflowCode,loginCode, "false", jsonObject.toString());

                        WorkflowNewRet ret = this.exworkflow(workflowParam);

                        if (ret.isSuccess()){


                            InstanceData destData = new InstanceData(AppUtility.getEngine(), ret.getInstanceID(), User.AdministratorID);

                            boolean b = sunlordService.custModify(sourceData, destData, subTabeCode);


                            if (b){
                                destData.getBizObject().setItem("INSTID",sourceData.getInstanceId());
                                destData.Submit();
                                result = RestfulApiResult.success("变更流程发起成功,请查看代办");
                            }else{
                                result = RestfulApiResult.success("变更流程发起失败,流程 复制失败");
                            }

                            result.setData(JSONObject.toJSONString(ret));

                        }else{
                            result = RestfulApiResult.fail("变更流程发起失败,流程开始失败");
                        }
                    }else{
                        result = RestfulApiResult.fail("变更流程发起失败,bpcnum 为空");
                    }
                }else{
                    result = RestfulApiResult.fail("变更流程发起失败,流程实例不存在");
                }
            }else{
                result = RestfulApiResult.fail("变更流程发起失败,instanceId,不存在");
            }
        } catch (Exception e) {
            e.printStackTrace();
            result = RestfulApiResult.fail("系统异常");
        }
        return result;
    }

    /**
     * 变更回写到主数据 根据 changeType 判断 指定 数据项修改数据
     * @param instanceId
     * @return
     */
    @RequestMapping(value = "custEditWritBack")
    public RestfulApiResult custEditWritBack(String instanceId){
        RestfulApiResult  result  ;

        try {
            if (instanceId != null && instanceId.trim().length()>0){
                InstanceData instanceData = new InstanceData(AppUtility.getEngine(), instanceId, User.AdministratorID);

                String changetypeValue = (String) instanceData.getBizObject().GetValue("CHANGETYPE");
                String instid = (String) instanceData.getBizObject().GetValue("INSTID");
                if (changetypeValue != null && instid != null){

                    InstanceData bpcInstance = new InstanceData(AppUtility.getEngine(), instid, User.AdministratorID);

                    SunlordResult rs = switchInstanceChangeSubmit(instanceData,bpcInstance,changetypeValue);

                    if (rs.isSuccess()){
                        //建档数据插入到x3 中间表
                        result = this.custMasterDataToX3(bpcInstance.getBizObject().getObjectID(),instanceData.getBizObject().getObjectID());

                    }else {
                        result = RestfulApiResult.fail(rs.getMsg());
                    }

                }else{
                    result = RestfulApiResult.fail("变更类型为空:"+instanceId);
                }

            }else {
                result = RestfulApiResult.fail("instanceid不符合规则:"+instanceId);
            }

        } catch (Exception e) {
            e.printStackTrace();
            result = RestfulApiResult.fail("系统错误");
        }
        return  result;
    }

    /**
     *  根据 changetypeValue 判断 修改值
     * @param instanceData
     * @param bpcInstance
     * @param changetypeValue
     * @return
     * @throws Exception
     */
    private SunlordResult switchInstanceChangeSubmit(InstanceData instanceData,InstanceData bpcInstance,String changetypeValue) throws Exception {
        SunlordResult rs = SunlordResult.success("");
        switch (changetypeValue){
            case "1" :
                String  rep0Chg = (String) instanceData.getBizObject().GetValue("REP_0_CHG");
                String  rep0ChgXs = (String) instanceData.getBizObject().GetValue("REP_0_CHG_XS");
                String ytrsfratioChg = (String) instanceData.getBizObject().GetValue("YTRSFRATIO_CHG");
                if (rep0Chg != null && rep0Chg.trim().length()>0  && ytrsfratioChg != null && ytrsfratioChg.trim().length()>0
                        && rep0ChgXs != null && rep0ChgXs.trim().length()>0){
                    bpcInstance.getBizObject().setItem("REP_0_XS",rep0ChgXs);
                    bpcInstance.getBizObject().setItem("REP_0",rep0Chg);
                    bpcInstance.getBizObject().setItem("YTRSFRATIO",ytrsfratioChg);
                    submit(bpcInstance);
                }else {
                    rs = SunlordResult.fail("业务员变更失败,变更数值不合法:instanceid"+instanceData.getInstanceId());
                }
                break;
            case "2" :
                String ostauzwchg = (String) instanceData.getBizObject().GetValue("OSTAUZWCHG");
                String ostauzChg = (String) instanceData.getBizObject().GetValue("OSTAUZ_CHG");
                if (ostauzwchg != null && ostauzwchg.trim().length()>0  && ostauzChg != null && ostauzChg.trim().length()>0){
                    bpcInstance.getBizObject().setItem("OSTAUZW",ostauzwchg);
                    bpcInstance.getBizObject().setItem("OSTAUZ",ostauzChg);
                    submit(bpcInstance);
                }else {
                    rs = SunlordResult.fail("信用额度变更,变更数值不合法:instanceid"+instanceData.getInstanceId());
                }
                break;
            case "3" :
                String pteChgXs = (String) instanceData.getBizObject().GetValue("PTE_CHG_XS");
                String pteChg = (String) instanceData.getBizObject().GetValue("PTE_CHG");
                String daymonChg = (String) instanceData.getBizObject().GetValue("DAYMON_CHG");
                String yzqdayChg = (String) instanceData.getBizObject().GetValue("YZQDAY_CHG");
                if (pteChgXs != null && pteChgXs.trim().length()>0  && pteChg != null && pteChg.trim().length()>0
                        && daymonChg != null && daymonChg.trim().length()>0 && yzqdayChg != null && yzqdayChg.trim().length()>0){
                    bpcInstance.getBizObject().setItem("PTE_XS",pteChgXs);
                    bpcInstance.getBizObject().setItem("PTE",pteChg);
                    bpcInstance.getBizObject().setItem("DAYMON",daymonChg);
                    bpcInstance.getBizObject().setItem("YZQDAY",yzqdayChg);
                    submit(bpcInstance);
                }else {
                    rs = SunlordResult.fail("付款条件变更,变更数值不合法:instanceid"+instanceData.getInstanceId());
                }
                break;
            case "4" :
                String yfcyChgXs = (String) instanceData.getBizObject().GetValue("YFCY_CHG_XS");
                String yfcyChg = (String) instanceData.getBizObject().GetValue("YFCY_CHG");
                if (yfcyChgXs != null && yfcyChgXs.trim().length()>0 && yfcyChg != null && yfcyChg.trim().length()>0){
                    bpcInstance.getBizObject().setItem("YFCY_XS",yfcyChgXs);
                    bpcInstance.getBizObject().setItem("YFCY",yfcyChg);
                    submit(bpcInstance);
                }else {
                    rs = SunlordResult.fail("交易窗口变更,变更数值不合法:instanceid"+instanceData.getInstanceId());
                }
                break;
            case "5" :
                String bprnamChg = (String) instanceData.getBizObject().GetValue("BPRNAM_CHG");
                if (bprnamChg != null && bprnamChg.trim().length()>0){
                    bpcInstance.getBizObject().setItem("BPRNAM",bprnamChg);
                    submit(bpcInstance);
                }else {
                    rs = SunlordResult.fail("客户名称变更,变更数值不合法:instanceid"+instanceData.getInstanceId());
                }
                break;
            case "6" :
                String bpcstaChgXs = (String) instanceData.getBizObject().GetValue("BPCSTA_CHG_XS");
                if (SunlordTrueFalse.SUNLORD_FALSE.equals(bpcstaChgXs)){
                    bpcInstance.getBizObject().setItem("BPCSTA",bpcstaChgXs);
                    bpcInstance.getBizObject().setItem("BPCSTA_XS","false");
                    submit(bpcInstance);
                }else {
                    rs = SunlordResult.fail("客户禁用,变更数值不合法:instanceid"+instanceData.getInstanceId());
                }
                break;
            case "7" :
                String bpcstaChgXs1 = (String) instanceData.getBizObject().GetValue("BPCSTA_CHG_XS");
                if ( SunlordTrueFalse.SUNLORD_TRUE.equals(bpcstaChgXs1)){
                    bpcInstance.getBizObject().setItem("BPCSTA",bpcstaChgXs1);
                    bpcInstance.getBizObject().setItem("BPCSTA_XS","true");
                    submit(bpcInstance);
                }else {
                    rs = SunlordResult.fail("客户解禁,变更数值不合法:instanceid"+instanceData.getInstanceId());
                }
                break;
            default:  rs = SunlordResult.fail("变更类型为空:"+instanceData.getInstanceId()+","+changetypeValue);
        }
        return  rs;
    }

    /**
     *  提交
     * @param bpcInstance
     * @throws Exception
     */
    private void submit(InstanceData bpcInstance) throws Exception {
        bpcInstance.getBizObject().setModifiedBy(User.AdministratorID);
        bpcInstance.getBizObject().setModifiedTime(new java.util.Date());

        bpcInstance.Submit();
    }

    /**
     * 获取 客户建档变更的 数据
     * @param sInstanceId
     * @return
     */
    @RequestMapping(value = "custFilingDataChange",method = RequestMethod.POST)
    public String custFilingDataChange(String sInstanceId){
        String result = JSON.toJSONString(RestfulApiResult.fail(""));

        try {

            UserValidator userValidator = getUserValidator();

            if(userValidator ==  null){
                return JSON.toJSONString(RestfulApiResult.fail("未登陆"));
            }

            InstanceContext instanceContext =getEngine().getInstanceManager().GetInstanceContext(sInstanceId);

            if(instanceContext == null) {
                return JSON.toJSONString(RestfulApiResult.fail("实例不存在"));
            }

            //实例数据sql
            List<Map<String, Object>> dataMaster = null;
            String sqlMaster = "SELECT * FROM I_BPCMASTER WHERE OBJECTID = '" + instanceContext.getBizObjectId()+"'";
            //企业经营状况
            List<Map<String, Object>> dataBussta = null;
            String sqlBussta = "SELECT * FROM I_BUSSTAMASTER WHERE PARENTOBJECTID =  '" + instanceContext.getBizObjectId()+"'";
            //收获地址
            List<Map<String, Object>> dataBpAddress = null;
            String sqlBpAddress = "SELECT * FROM I_BPADDRESSMASTER WHERE PARENTOBJECTID =  '" + instanceContext.getBizObjectId()+"'";
            //联系人sql
            List<Map<String, Object>> dataContact = null;
            String sqlContact = "SELECT * FROM I_CONTACTMASTER WHERE PARENTOBJECTID =  '" + instanceContext.getBizObjectId()+"'";
            //关联企业sql
            List<Map<String, Object>> dataCrmbpc = null;
            String sqlCrmbpc ="SELECT * FROM I_CRMBPCMASTER WHERE PARENTOBJECTID =  '" + instanceContext.getBizObjectId()+"'";
            //客户产品属性
            List<Map<String, Object>> dataCrmbpcitm = null;
            String sqlCrmbpcitm ="SELECT * FROM I_CRMBPCITMMASTER WHERE PARENTOBJECTID =  '" + instanceContext.getBizObjectId()+"'";


            Query query = ControllerBase.getEngine().getQuery();
            dataMaster = analysisBizObjectToListMap(query.QueryTable(sqlMaster));
            if(dataMaster.isEmpty() || dataMaster.size()>1){
                return JSON.toJSONString(("转换实例数据异常："+dataMaster.size()));
            }
            loadAttachment(query,dataMaster,instanceContext.getBizObjectSchemaCode());

            dataBussta = analysisBizObjectToListMap(query.QueryTable(sqlBussta)) ;

            dataBpAddress = analysisBizObjectToListMap(query.QueryTable(sqlBpAddress)) ;
            loadAttachment(query,dataBpAddress,instanceContext.getBizObjectSchemaCode());

            dataContact = analysisBizObjectToListMap(query.QueryTable(sqlContact));
            dataCrmbpc = analysisBizObjectToListMap(query.QueryTable(sqlCrmbpc));
            dataCrmbpcitm = analysisBizObjectToListMap(query.QueryTable(sqlCrmbpcitm));

            JSONObject paramValues  = new JSONObject();
            paramValues.put("BPCCHG",JSON.parseObject(JSON.toJSONString(dataMaster.get(0), SerializerFeature.WriteMapNullValue)));
            paramValues.put("BUSSTACHG",JSON.parseArray(JSON.toJSONString(dataBussta, SerializerFeature.WriteMapNullValue)));
            paramValues.put("BPADDRESSCHG", JSON.parseArray(JSON.toJSONString(dataBpAddress, SerializerFeature.WriteMapNullValue)));
            paramValues.put("CONTACTCHG", JSON.parseArray(JSON.toJSONString(dataContact, SerializerFeature.WriteMapNullValue)));
            paramValues.put("CRMBPCCHG", JSON.parseArray(JSON.toJSONString(dataCrmbpc, SerializerFeature.WriteMapNullValue)));
            paramValues.put("CRMBPCITMCHG", JSON.parseArray(JSON.toJSONString(dataCrmbpcitm, SerializerFeature.WriteMapNullValue)));

            result = JSON.toJSONString(RestfulApiResult.success(paramValues), SerializerFeature.WriteMapNullValue) ;

        } catch (Exception e) {
            e.printStackTrace();
            LOGGER.error(e.getMessage());
        }
        return  result;
    }


    /**
     *  dataTable 转 listMap
     * @param dataTable
     * @return
     */
    private List<Map<String,Object>> analysisBizObjectToListMap(DataTable dataTable) throws DataException {
        DataColumnCollection columns = dataTable.getColumns();
        DataRowCollection rows = dataTable.getRows();
        List<Map<String,Object>> list = new ArrayList<>((int)(rows.size()/0.75));
        HashMap<String, Object> hashMap = null;
        int mapSize = columns.size() >16 ?(int)(columns.size()/0.75):16;
        String colName ;
        for (int i = 0; i < rows.size(); i++) {
            hashMap = new HashMap<>(mapSize);
            for (int j = 0; j < columns.size(); j++) {
                colName = columns.get(j).getColumnName();
                hashMap.put(colName,
                        rows.get(i).getObject(colName));

            }
            list.add(hashMap);
        }
        return list;
    }

    /**
     * 查询附件
     * @param query
     * @param list
     * @param schemaCode
     */
    public void loadAttachment(Query query, List<Map<String, Object>> list,String schemaCode) throws DataException {
        //附件
        String fileSql = "select OBJECTID,FILENAME,BIZOBJECTID,BIZOBJECTSCHEMACODE,CONTENTTYPE,DATAFIELD,CONTENTLENGTH,DOWNLOADURL from OT_Attachment WHERE BIZOBJECTSCHEMACODE ='%s' and BIZOBJECTID='%s'" ;

        List<Map<String, Object>> fileList ;
        Map<String, Object> data;
        String dataField;
        for (int i = 0; i < list.size(); i++) {
            fileList = analysisBizObjectToListMap(query.QueryTable(String.format(fileSql, schemaCode,list.get(i).get("OBJECTID"))));
            if (!fileList.isEmpty()){
                data = list.get(i);
                for (int j = 0; j < fileList.size(); j++) {
                    if(fileList.get(j).get("DATAFIELD")==null || (dataField=fileList.get(j).get("DATAFIELD").toString()).trim().length()==0) {
                        continue;
                    }
                    if(data.get(dataField) == null || !(data.get(dataField) instanceof  List)){
                        data.put(dataField,new ArrayList<>());
                    }
                    ((List)data.get(dataField)).add(covFileData(fileList.get(j)));
                }

            }
        }
    }

    /**
     *
     * @param data
     * @return
     */
    private Map<String,Object> covFileData (Map<String,Object> data){
        /*"Code": "4c943fb0-6b72-43a2-a921-6f58a5ad04e5",
        "ContentType": "application/x-msdownload",
        "Name": "wpscloudsvr.exe",
        "Size": 360104,
        "Url":*/
        String url = "/Portal/ReadAttachment/Read?BizObjectSchemaCode=%s&BizObjectID=%s&AttachmentID=%s&OpenMethod=0";
        Map<String, Object> covFileData = new HashMap<>(8);
        covFileData.put("Code",data.get("OBJECTID"));
        covFileData.put("ContentType",data.get("CONTENTTYPE"));
        covFileData.put("Name",data.get("FILENAME"));
        covFileData.put("Size",data.get("CONTENTLENGTH"));
        covFileData.put("Url", String.format(url, data.get("BIZOBJECTSCHEMACODE"),data.get("BIZOBJECTID"),data.get("OBJECTID")));
        covFileData.put("downloadUrl",data.get("DOWNLOADURL"));
        return covFileData;
    }

    @Override
    public String getFunctionCode() {
        return null;
    }



    public String test(){



        return "";
    }


}

